package com.demo.crm.springboot3security.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.demo.crm.springboot3security.entity.CustomForm;
import com.demo.crm.springboot3security.mapper.CustomFormMapper;
import com.mybatisflex.core.query.QueryWrapper;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class CacheWarmupService {

    private final CustomFormMapper customFormMapper;
    private final FormDataService formDataService;

    @EventListener(ApplicationStartedEvent.class)
    public void warmupOnStartup() {
        log.info("开始预热缓存...");
        List<CustomForm> forms = customFormMapper.selectListByQuery(QueryWrapper.create());
        
        CompletableFuture[] futures = forms.stream()
                .map(this::warmupFormCache)
                .toArray(CompletableFuture[]::new);

        CompletableFuture.allOf(futures)
                .thenRun(() -> log.info("缓存预热完成"))
                .exceptionally(throwable -> {
                    log.error("缓存预热失败", throwable);
                    return null;
                });
    }

    @Async
    protected CompletableFuture<Void> warmupFormCache(CustomForm form) {
        try {
            // 预热查询缓存
            Map<String, Object> queryConditions = new HashMap<>();
            formDataService.advancedQuery(form, queryConditions, null, 1, 10);

            // 预热聚合缓存
            Map<String, String> aggregates = new HashMap<>();
            aggregates.put("id", "count");
            formDataService.aggregate(form, null, aggregates, null);

            log.info("表单[{}]缓存预热完成", form.getName());
            return CompletableFuture.completedFuture(null);
        } catch (Exception e) {
            log.error("表单[{}]缓存预热失败", form.getName(), e);
            return CompletableFuture.failedFuture(e);
        }
    }
} 